package com.emm.yixun.mobile.ui.analysis;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetProjectList.ProjectList;
import com.emm.yixun.mobile.model.GetStockTimeList;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.PercentFormatter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 存量时间分析
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:12:44
 */
public class TimeAnalysisActivity extends SwipeBackActivity implements OnChartValueSelectedListener {

	private static final String TAG = "TimeAnalysisActivity";

	/** 类目布局模块 */
	LinearLayout sort_textview;

	/** 类目箭头 */
	ImageView icon1, icon2;

	/** 顶部日期模块 */
	LinearLayout screen_textview;

	/** 顶部类目 */
	TextView set_type, colors_text2;

	TextView null_date4;

	/** 扇形图 */
	private PieChart mChart;

	/** 数据列表 */
	private ArrayList<String> list = new ArrayList<String>();
	private ArrayList<String> list3 = new ArrayList<String>();

	/** 数据列表每项所对应的百分比 */
	private ArrayList<Float> list2 = new ArrayList<Float>();

	TextView title_main;

	ImageView back_btn;

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	@Override
	protected void onResume() {
		BaseActivity.activity = this; // TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.time_analysis_activity);

		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;
		SetColor();
		initView();

		SetRelativiLayoutPadding(R.id.main_head_top_rela);

		initBtn();
		getStockTimeList("1", "1");
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:00:01
	 */
	private void initView() {
		sort_textview = (LinearLayout) findViewById(R.id.sort_textview);
		icon1 = (ImageView) findViewById(R.id.icon1);
		screen_textview = (LinearLayout) findViewById(R.id.screen_textview);
		icon2 = (ImageView) findViewById(R.id.icon2);
		set_type = (TextView) findViewById(R.id.set_type);
		colors_text2 = (TextView) findViewById(R.id.colors_text2);
		mChart = (PieChart) findViewById(R.id.chart1);
		mChart.setNoDataText(" ");
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText("存量时间分析");
		back_btn = (ImageView) findViewById(R.id.back_btn);
		null_date4 = (TextView) findViewById(R.id.null_date4);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:00:42
	 */
	private void initBtn() {
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		sort_textview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				set_type.setTextColor(Color.parseColor("#FCA639"));
				colors_text2.setTextColor(Color.parseColor("#3E3C3D"));
				icon1.setImageResource(R.drawable.paixu_down);
				icon2.setImageResource(R.drawable.paixu_up);
				SetsortPopu(set_type, 1);
			}
		});

		screen_textview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				set_type.setTextColor(Color.parseColor("#3E3C3D"));
				colors_text2.setTextColor(Color.parseColor("#FCA639"));
				icon1.setImageResource(R.drawable.paixu_up);
				icon2.setImageResource(R.drawable.paixu_down);
				SetsortPopu(colors_text2, 0);
			}
		});
	}

	/** 时间类型 */
	int timeTypeCount = 0;

	/** 类目类型 */
	int categoryTypeCount = 0;
	View viewproject;
	PopupWindow popuproject;

	/** 选中的类型 */
	private int SelectPostion = 0;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 条件选择弹出框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param tv
	 * @param type
	 * @author tangxin
	 * @date 2016年12月7日 下午5:08:38
	 */
	public void SetsortPopu(final TextView tv, final int type) {
		viewproject = LayoutInflater.from(TimeAnalysisActivity.this).inflate(R.layout.mainproject_popu, null);
		popuproject = new PopupWindow(viewproject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popuproject.setFocusable(true);
		popuproject.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popuproject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popuproject.showAtLocation(sort_textview, Gravity.TOP, 0, 0);
		popuproject.setFocusable(true);
		popuproject.setOutsideTouchable(true);
		viewproject.setFocusable(true);
		viewproject.setFocusableInTouchMode(true);
		viewproject.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popuproject.dismiss();
					EmmApplication.setLog(TimeAnalysisActivity.this);
				}
				return false;
			}
		});
		viewproject.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popuproject.dismiss();
				EmmApplication.setLog(TimeAnalysisActivity.this);
			}
		});
		ListView popu_list = (ListView) viewproject.findViewById(R.id.popu_list);
		RelativeLayout top_relativelayout = (RelativeLayout) viewproject.findViewById(R.id.top_relativelayout);
		SetViewPaddingHeight(top_relativelayout, 95);
		final GetProjectList list = new GetProjectList();
		ArrayList<ProjectList> ll = new ArrayList<ProjectList>();

		if (type == 0) {
			ProjectList m = new ProjectList();
			m.setProjectCode("1");
			m.setProjectName("公寓");
			ll.add(m);

			ProjectList m2 = new ProjectList();
			m2.setProjectCode("2");
			m2.setProjectName("别墅");
			ll.add(m2);

			ProjectList m3 = new ProjectList();
			m3.setProjectCode("3");
			m3.setProjectName("车位");
			ll.add(m3);
		} else {
			for (int i = 0; i < 24; i++) {
				ProjectList m = new ProjectList();
				m.setProjectCode((i + 1) + "");
				m.setProjectName((i + 1) + "个月");
				ll.add(m);
			}
		}
		list.setProjectList(ll);
		MainProjectAdapter adapter = new MainProjectAdapter(TimeAnalysisActivity.this, list);
		popu_list.setAdapter(adapter);
		if (type == 0) {
			if (list.getProjectList().size() >= (categoryTypeCount + 1)) {
				adapter.SeleCt(categoryTypeCount);
				tv.setText(list.getProjectList().get(categoryTypeCount).getProjectName());
			} else {
				adapter.SeleCt(0);
				tv.setText(list.getProjectList().get(0).getProjectName());
			}
		} else {
			if (list.getProjectList().size() >= (timeTypeCount + 1)) {
				adapter.SeleCt(timeTypeCount);
				tv.setText(list.getProjectList().get(timeTypeCount).getProjectName());
			} else {
				adapter.SeleCt(0);
				tv.setText(list.getProjectList().get(0).getProjectName());
			}
		}
		adapter.SetType(1);
		popu_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				SelectPostion = position;
				popuproject.dismiss();
				EmmApplication.setLog(TimeAnalysisActivity.this);
				tv.setText(list.getProjectList().get(position).getProjectName());
				if (type == 0) {// 类目类型
					categoryTypeCount = position;
				} else {// 时间类型
					timeTypeCount = position;
				}
				Log.v(TAG, "timeTypeCount:" + timeTypeCount + "/-->categoryTypeCount:" + categoryTypeCount);
				getStockTimeList("" + (timeTypeCount + 1), "" + (categoryTypeCount + 1));

			}
		});
	}

	/**
	 * 存量时间分析
	 */
	GetStockTimeList getstock;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 存量时间分析
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param monthlyLimit
	 * @param propertyType
	 * @author tangxin
	 * @date 2016年12月7日 下午5:09:35
	 */
	private void getStockTimeList(String monthlyLimit, String propertyType) {
		EmmApplication.updateUrl("getStockTimeList");
		Map<String, String> map = new HashMap<String, String>();

		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("monthlyLimit", monthlyLimit);
		map.put("propertyType", propertyType);

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getStockTimeList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(TimeAnalysisActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, "content===>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getstock = JSONObject.parseObject(resData.toString(), GetStockTimeList.class);

				if ("1".equals(getstock.getResult())) {
					Log.v("获取成功", "");
					if (null != getstock.getStockTimeList()) {
						list.clear();
						list2.clear();
						list3.clear();
						double countall = 0;
						for (int i = 0; i < getstock.getStockTimeList().size(); i++) {
							countall += Double.valueOf(getstock.getStockTimeList().get(i).getStockTimeNum())
									.doubleValue();
						}
						if (countall > 0) {
							null_date4.setVisibility(View.INVISIBLE);
							for (int i = 0; i < getstock.getStockTimeList().size(); i++) {
								list.add(getstock.getStockTimeList().get(i).getStockTimeName());
								list2.add((float) (Double.valueOf(getstock.getStockTimeList().get(i).getStockTimeNum())
										.doubleValue() / countall) * 100);
								// 需要计算百分比
								list3.add(getstock.getStockTimeList().get(i).getStockTimeNum());
							}
							SetSettingChart(0);
							animate();
						} else {
							null_date4.setVisibility(View.VISIBLE);
							EmmApplication.T("获取数据为空");
							list.clear();
							list3.clear();
							list2.clear();
							SetSettingChart(1);
							animate();
						}
					} else {
						null_date4.setVisibility(View.VISIBLE);
						EmmApplication.T("获取数据为空");
						list.clear();
						list2.clear();
						SetSettingChart(1);
						animate();
					}
				} else {
					EmmApplication.T(getstock.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getstock.getErrorCode().toString() + "errorMsg:"
							+ getstock.getErrorMsg().toString());
				}
			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 配置扇形图属性,第一次在加载数据完成之后触发
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param type
	 * @author tangxin
	 * @date 2016年12月7日 下午5:03:24
	 */
	private void SetSettingChart(int type) {
		mChart.setUsePercentValues(true);
		mChart.setHoleColorTransparent(true);
		mChart.setHoleRadius(55);
		if (type == 0) {
			mChart.setHoleColor(Color.parseColor("#ffffff"));
			mChart.setCenterText("100%");
		} else {
			mChart.setHoleColor(Color.parseColor("#00ffffff"));
			mChart.setCenterText(" ");
		}
		mChart.setDescription("");
		mChart.setDrawCenterText(true);
		mChart.setDrawHoleEnabled(true);
		mChart.setRotationAngle(0);
		mChart.setRotationEnabled(true);
		mChart.setOnChartValueSelectedListener(this);
		mChart.setX(EmmApplication.dip2pxf(-100));
		setData();
		mChart.animateXY(1000, 1000);
		Legend l = mChart.getLegend();
		l.setPosition(LegendPosition.RIGHT_OF_CHART);
		l.setXEntrySpace(20f);
		l.setYEntrySpace(4f);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 调用动画效果
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:03:36
	 */
	private void animate() {
		mChart.invalidate();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 给统计图设置数据
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:03:42
	 */
	private void setData() {
		ArrayList<Entry> yVals1 = new ArrayList<Entry>();
		for (int i = 0; i < list2.size(); i++) {
			yVals1.add(new Entry(list2.get(i), i));
		}
		ArrayList<String> xVals = new ArrayList<String>();

		PieDataSet dataSet = new PieDataSet(yVals1, "");
		dataSet.setSliceSpace(3f);
		for (int i = 0; i < list.size(); i++)
			xVals.add(list.get(i) + "\t\t" + list3.get(i) + "\t\t"
					+ ("(" + EmmApplication.drop2("" + list2.get(i)) + "%" + ")"));
		dataSet.setDrawValues(false);
		mChart.setDrawSliceText(false);
		ArrayList<Integer> colors = new ArrayList<Integer>();

		for (int i = 0; i < list.size(); i++) {
			colors.add(bgcolor.get(i));
		}

		dataSet.setColors(colors);
		PieData data = new PieData(xVals, dataSet);
		data.setValueFormatter(new PercentFormatter());
		data.setValueTextSize(11f);
		data.setValueTextColor(Color.BLACK);
		mChart.setData(data);
		mChart.highlightValues(null);
		mChart.setNoDataTextDescription(" ");
		mChart.invalidate();
	}

	ArrayList<Integer> bgcolor = new ArrayList<Integer>();

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 统计图色值初始化
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:03:55
	 */
	private void SetColor() {
		bgcolor.add(Color.parseColor("#FFE76E"));
		bgcolor.add(Color.parseColor("#FFC499"));
		bgcolor.add(Color.parseColor("#FFB468"));
		bgcolor.add(Color.parseColor("#FF9048"));
		bgcolor.add(Color.parseColor("#F64A2A"));
		bgcolor.add(Color.parseColor("#FA7388"));
		bgcolor.add(Color.parseColor("#F63C7F"));
		bgcolor.add(Color.parseColor("#F43560"));
		bgcolor.add(Color.parseColor("#CC1F1A"));
		bgcolor.add(Color.parseColor("#740D0C"));
		bgcolor.add(Color.parseColor("#C6F4FF"));
		bgcolor.add(Color.parseColor("#67C3D5"));
		bgcolor.add(Color.parseColor("#5199AA"));
		bgcolor.add(Color.parseColor("#009796"));
		bgcolor.add(Color.parseColor("#009868"));
		bgcolor.add(Color.parseColor("#8CD3E7"));
		bgcolor.add(Color.parseColor("#1FBBD3"));
		bgcolor.add(Color.parseColor("#006EA8"));
		bgcolor.add(Color.parseColor("#005AA6"));
		bgcolor.add(Color.parseColor("#5B5377"));
	}

	public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
		if (e == null)
			return;
		Log.i("VAL SELECTED", "Value: " + e.getVal() + ", xIndex: " + e.getXIndex() + ", DataSet index: "
				+ dataSetIndex);
	}

	public void onNothingSelected() {
		Log.i("PieChart", "nothing selected");
	}
}
